package com.boy.rpc.framework.console;

import com.boy.rpc.framework.console.exception.RedisInitException;
import com.boy.rpc.framework.console.exception.ZkInitException;
import com.boy.rpc.framework.console.utils.InitZkConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Properties;

/**
 * Created by wesley on 2017-04-06.
 */
public class ZookeeperApplication implements ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(ZookeeperApplication.class);

    private Properties properties;

    public ZookeeperApplication(){
    }

    public ZookeeperApplication(Properties properties){
        this.properties = properties;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        logger.debug("Zookeeper Server ---- start!!!");
        String currentServerName = "";
        try {
            int serverNum = Integer.parseInt(properties.getProperty(Constant.ZK_PROPERTIES_SERVER_NUM_KEY));
            String keys = properties.getProperty(Constant.ZK_PROPERTIES_NODE_PRXFIX_KEY);
            for(int i=1;i<=serverNum;i++) {
                String name = properties.getProperty(Constant.ZK_PROPERTIES_NAME_PREFIX_KEY + i);
                String host = properties.getProperty(Constant.ZK_PROPERTIES_HOST_PREFIX_KEY + i);
                int port = Integer.parseInt(properties.getProperty(Constant.ZK_PROPERTIES_PORT_PREFIX_KEY + i));
                currentServerName = name;
                InitZkConnection.createZKConnection(host+":"+port,keys);
            }
            logger.debug("zk currentServerName---->>"+currentServerName);
        } catch (NumberFormatException e) {
            logger.error("initZkServers: " + currentServerName+" occur NumberFormatException :" + e.getMessage());
            throw new ZkInitException(e);
        } catch (Throwable e1) {
            logger.error("initZkServers: " + currentServerName+" occur Throwable :" + e1.getMessage());
            throw new ZkInitException(currentServerName + " init failed", e1);
        }
    }
}
